package com.chenyi.web.controller.system;

import com.chenyi.common.annotation.Log;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.controller.BaseController;
import com.chenyi.common.core.domain.entity.SysAdminMenu;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.enums.BusinessType;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.AdminUtils;
import com.chenyi.common.utils.ServletUtils;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.framework.web.service.AdminTokenService;
import com.chenyi.system.service.ISysAdminMenuService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 * 
 * @author wangkh
 */
@RestController
@RequestMapping("/admin/menu")
public class AdminMenuController extends BaseController
{
    @Autowired
    private ISysAdminMenuService menuService;

    @Autowired
    private AdminTokenService tokenService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@admin.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public ResponseEntity<Object> list(SysAdminMenu menu)
    {
        LoginAdmin loginAdmin = tokenService.getLoginAdmin(ServletUtils.getRequest());
        Long userId = loginAdmin.getAdmin().getAdminId();
        List<SysAdminMenu> menus = menuService.selectAdminMenuList(menu, userId);
        return ResponseEntity.ok(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@admin.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public ResponseEntity<Object> getInfo(@PathVariable Long menuId)
    {
        return ResponseEntity.ok(menuService.selectAdminMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public ResponseEntity<Object> treeselect(SysAdminMenu menu)
    {
        LoginAdmin loginAdmin = tokenService.getLoginAdmin(ServletUtils.getRequest());
        Long userId = loginAdmin.getAdmin().getAdminId();
        List<SysAdminMenu> menus = menuService.selectAdminMenuList(menu, userId);
        return ResponseEntity.ok(menuService.buildAdminMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public ResponseEntity<Object> roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        LoginAdmin loginUser = tokenService.getLoginAdmin(ServletUtils.getRequest());
        List<SysAdminMenu> menus = menuService.selectAdminMenuList(loginUser.getAdmin().getAdminId());
        Map<String,Object> data = Maps.newHashMap();
        data.put("checkedKeys", menuService.selectAdminMenuListByRoleId(roleId));
        data.put("menus", menuService.buildAdminMenuTreeSelect(menus));
        return ResponseEntity.ok(data);
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@admin.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseEntity<Object> add(@Validated @RequestBody SysAdminMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkAdminMenuNameUnique(menu)))
        {
            throw new MessageException("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            throw new MessageException("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(AdminUtils.getUsername());
        menuService.insertAdminMenu(menu);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@admin.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Object> edit(@Validated @RequestBody SysAdminMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkAdminMenuNameUnique(menu)))
        {
            throw new MessageException("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            throw new MessageException("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            throw new MessageException("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(AdminUtils.getUsername());
        menuService.updateAdminMenu(menu);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@admin.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public ResponseEntity<Object> remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            throw new MessageException("存在子菜单,不允许删除");
        }
        if (menuService.checkAdminMenuExistRole(menuId))
        {
            throw new MessageException("菜单已分配,不允许删除");
        }
        menuService.deleteAdminMenuById(menuId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}